import { createRouter, createWebHashHistory, RouteRecordName, RouteRecordRaw } from 'vue-router'
import { useRouterList } from '../stores/modules/routerList'
import { store } from '@/stores/index'
import { getToken } from '@/utils/auth'
const { setAuthRouter, setDefaultRouter } = useRouterList(store)
const modules: Record<string, any> = import.meta.glob(['./modules/**/*.ts'], {
  eager: true
})
/** 原始静态路由（未做任何处理） */
const routes: Array<any> = []

Object.keys(modules).forEach((key) => {
  routes.push(modules[key].default)
})

const remainingPaths: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
]

// 是否是首次加载路由
let isFirstLoading = true
const router = createRouter({
  history: createWebHashHistory(),
  routes: remainingPaths
})
const whiteList = ['/login']
router.beforeEach((to, from) => {
  // 首次进入路由添加动态路由
  if (isFirstLoading) {
    setDefaultRouter(remainingPaths)
    routes.forEach((item) => {
      router.addRoute(item)
    })
    // 添加路由后改变状态
    isFirstLoading = false
    setAuthRouter(routes)
    return to.fullPath
  }
  if (whiteList.includes(to.fullPath)) return true
  else if (!getToken()) return { path: '/login' }
  else if (router.hasRoute(to.name as RouteRecordName)) return true
  else return { path: '/error/404' }
})
export default router
